package com.wangtongxiao.interceptor;

import com.wangtongxiao.beans.User;
import com.wangtongxiao.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class MyLoginInterceptor implements HandlerInterceptor {

    @Autowired
    @Qualifier("UserServicesFilter")
    UserServices userServices;

    //    请求之前    ture继续请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        HttpSession session = request.getSession();
        User login = (User) session.getAttribute("user");
        if (login == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies==null){
                response.sendRedirect("/static/login.html");
                return false;

            }

            String loginAct = "";
            String loginPwd = "";
            for (Cookie cookie : cookies) {

                if (cookie.getName().equals("loginAct")) {
                    loginAct = cookie.getValue();
                }
                if (cookie.getName().equals("loginPwd")) {
                    loginPwd = cookie.getValue();
                }
            }
            User loginTem = userServices.login(loginAct, loginPwd);
            if (loginTem==null){
                response.sendRedirect("/static/login.html");
                return false;
            }
            else {
                session.setAttribute("user",loginTem);
                return true;
        }
        }else {
            return true;
        }
    }

    //响应结束，没到浏览器
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //结束
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
